package com.xiaomaoguai.springmvc.controller;

import java.io.IOException;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

@Controller
public class IndexController {

	@RequestMapping(value = "/index", method = { RequestMethod.GET })
	public ModelAndView index() {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("message", "Hello World!");
		modelAndView.setViewName("index");
		return modelAndView;
	}

	/**
	 * 
	 * @Name: callback
	 * @Description:jsonp跨域请求
	 * @Author: WeiHui.Zhang
	 * @Version: V1.00
	 * @Date: 2016年2月25日上午11:51:52
	 * @param list
	 * @return
	 * @throws JsonProcessingException
	 * @Return: String
	 */
	@RequestMapping(value = "/callback", method = { RequestMethod.GET })
	@ResponseBody
	public String callback(ListModel list) throws JsonProcessingException {
		List<User> list2 = list.getList();
		for (User user : list2) {
			System.out.println(user);
		}
		String callback = list.getCallback();
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(list2);
		String result = callback + "(" + json + ")";
		System.out.println(result);
		return result;
	}

	/**
	 * 
	 * @Name: index
	 * @Description:json参数的例子
	 * @Author: WeiHui.Zhang
	 * @Version: V1.00
	 * @Date: 2016年2月25日上午11:52:13
	 * @return
	 * @Return: ModelAndView
	 */
	@RequestMapping(value = "/testjson", method = { RequestMethod.GET })
	public String testjson(String param) {
		ObjectMapper objectMapper = new ObjectMapper();
		// User user;
		try {
			// 单个
			// user = objectMapper.readValue(param, User.class);

			TypeReference<List<User>> typeReference = new TypeReference<List<User>>() {
			};

			// 多个对象
			List<User> users = objectMapper.readValue(param, typeReference);

			for (User user2 : users) {

				System.out.println(user2);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "test";
	}
}
